var addressGraphicLayer;
var initAddressSearch;
var addressSearchText;
var localStorage = window.localStorage;
var isAddressSearch = false
require([
    "dojo/on", "dojo/_base/connect",
    "esri/symbols/PictureMarkerSymbol", "esri/layers/GraphicsLayer",
    "esri/graphic", "esri/InfoTemplate",
    "esri/geometry/Point",
    "dojo/domReady!"
], function (
    on, connect, PictureMarkerSymbol, GraphicsLayer, Graphic,
    InfoTemplate, Point) {

    initAddressSearch = function () {
        addressGraphicLayer = new GraphicsLayer({
            id: "addressGraphicLayer"
        });
        map.addLayer(addressGraphicLayer);

        addressGraphicLayer.on("click", function (e) {
            aroundSearchCenterGraphic = e.graphic
            map.infoWindow.hide();
        })

        if (localStorage.getItem("historyAddressArray") == null) {
            localStorage.setItem("historyAddressArray", JSON.stringify([]));
        }
    }

    //历史搜索记录
    $("#menpaiInput").click(function () {
        showHistoryList()
    })

    function showHistoryList() {
        const a = $("#menpaiInput").val();
        if ($("#menpaiInput").val() !== "") {
            return
        }
        $("#historyaAdressList>ul").empty();

        let historyAddressArray = JSON.parse(localStorage.getItem('historyAddressArray'));

        if (historyAddressArray.length > 0) {
            $("#historyaAdressList").show()

            historyAddressArray.reverse().forEach((item, index) => {
                var li = document.createElement("li");
                li.id = "historyitem_" + index;
                var corp_name = document.createElement("p");
                corp_name.className = "history_item";
                corp_name.innerHTML = `<img class='historyImg' src='img/history record.png'/>${item}
                                     <a id='del_history_${index}' class='close'>×</a>`;
                li.appendChild(corp_name);
                $("#historyaAdressList>ul").append(li);

                $(li).click(function () {
                    $("#menpaiInput").val(item)
                    doAddressSearch(item)
                })

                $(`#del_history_${index}`).click(function (e) {
                    historyAddressArray.splice(index, 1)
                    localStorage.setItem('historyAddressArray', JSON.stringify(historyAddressArray.reverse()));
                    showHistoryList()
                    e.stopPropagation();
                })
            })

            var li = document.createElement("li");
            li.id = "historyEmpty";
            var corp_name = document.createElement("p");
            corp_name.className = "history_item";
            corp_name.innerHTML = `清除所有历史记录`;

            li.appendChild(corp_name);
            $("#historyaAdressList>ul").append(li);

            $(li).click(function () {
                localStorage.setItem("historyAddressArray", JSON.stringify([]));
                showHistoryList()
            })
        }

    }

    $(".input_clear").click(function () {
        closePanel()
        $("#addressSearchBtn").hide();
        $("#addressSearchPanel").show();
        resetBtnPosition()
    })


    //地址检索
    $("#addressSearchBtn").click(function () {
        $("#addressSearchBtn").hide();
        $("#addressSearchPanel").show();
        resetBtnPosition()
    });

    $("#menpaiInput").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $("#menpaiSearBtn").click();
        }
    })

    var addressResult = [];
    $("#menpaiSearBtn").click(function () {
        addressSearchText = $("#menpaiInput").val();
        if (addressSearchText.trim().length === 0) {
            $("#menpaiInput").focus();
            return;
        }
        doAddressSearch(addressSearchText)
    });

    function doAddressSearch(addressSearchText) {
        //存储搜索历史
        historyAddressArray = JSON.parse(localStorage.getItem('historyAddressArray'));

        function isInHistoryAddressArray(text) {
            return text === addressSearchText;
        }
        const index = historyAddressArray.findIndex(isInHistoryAddressArray);
        if (index !== -1) {
            historyAddressArray.splice(index, 1)
        }
        historyAddressArray.push(addressSearchText)
        localStorage.setItem('historyAddressArray', JSON.stringify(historyAddressArray));

        $("#historyaAdressList").hide()
        $("#addressList>ul").empty();
        $("#addressList .waitPanel").show();
        $("#addressPage").empty();

        $.ajax({
            // url: oneMapServerIPproxy+"/OneMapServer/rest/services/address_p/as_CH.asmx/ASCH_AddressSearch?vSearch_word=" + addressSearchText + "&vResult_count=1000&token=" + GLOBAL_TOKEN,
            url: oneMapServerIPproxy+"/OneMapServer/rest/services/address/as_ch.asmx/ASCH_AddressSearch?vSearch_word=" + addressSearchText + "&vSearch_class=&vSearch_region=&vSearch_year=&vResult_count=300&token=" + GLOBAL_TOKEN,
            type: "get",
            dataType: "XML",
            success: function (response) {
                map.infoWindow.hide();
                $("#addressList .waitPanel").hide();
                $("#addressList").show();

                if (response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("Result_Flag").length == 0) {
                    var sli = "<li><span class='data_count'>在上海市范围内未找到相关地点。</span></li>"
                    $("#addressList>ul").append(sli);
                    return;
                }
                addressResult = response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("DZ_Table")[0].children[1].children[0].children;

                if (addressResult.length > 0) {
                    $("#addressPage").initPage(addressResult.length, 1, buildAddress);
                }
            }
        });
    }

    var onePageCount = 10

    //构建搜索结果内容
    function buildAddress(page) {
        isAddressSearch = true

        $("#addressList>ul").empty();
        var sli = "<li><span class='data_count'>共有" + addressResult.length + "个结果</span>" +
            "</li>"
        $("#addressList>ul").append(sli);
        addressGraphicLayer.clear();

        var max = page * onePageCount;

        if (max > addressResult.length) {
            max = addressResult.length
        }

        let addressGraphics = []
        for (let i = (page - 1) * onePageCount; i < max; i++) {
            var item = addressResult[i];
            var attr = {};

            //统一名称
            var addname = "";

            if (null != item.getElementsByTagName("POI")[0] && item.getElementsByTagName("POI")[0].textContent != null) {
                addname = item.getElementsByTagName("POI")[0].textContent;
            } else if (null != item.getElementsByTagName("ROAD1")[0] && item.getElementsByTagName("ROAD1")[0].textContent != null) {
                addname = item.getElementsByTagName("ROAD1")[0].textContent;
            } else if (null != item.getElementsByTagName("ADDRESS")[0] && item.getElementsByTagName("ADDRESS")[0].textContent != null) {
                addname = item.getElementsByTagName("ADDRESS")[0].textContent;
            }

            if (null != item.getElementsByTagName("POINT_X")[0] && item.getElementsByTagName("POINT_X")[0].textContent != null && null != item.getElementsByTagName("POINT_Y")[0] && item.getElementsByTagName("POINT_Y")[0].textContent != null) {
                var x = parseFloat(item.getElementsByTagName("POINT_X")[0].textContent);
                var y = parseFloat(item.getElementsByTagName("POINT_Y")[0].textContent);
            } else {
                return
            }

            var area = "";

            if (null != item.getElementsByTagName("REGION_QX")[0] && item.getElementsByTagName("REGION_QX")[0].textContent != null) {
                area = item.getElementsByTagName("REGION_QX")[0].textContent;
            } else {
                area = "上海市";
            }

            var maccuracy = "";
            if (null != item.getElementsByTagName("MACCURACY")[0] && item.getElementsByTagName("MACCURACY")[0].textContent != null) {
                maccuracy = item.getElementsByTagName("MACCURACY")[0].textContent;
            } else {
                maccuracy = "0";
            }

            attr["name"] = addname;
            attr["district"] = area;
            attr["x"] = x;
            attr["y"] = y;
            attr["maccuracy"] = maccuracy;

            var sms = new PictureMarkerSymbol("img/marker2/" + (i + 1 - (page - 1) * onePageCount) + ".png", 30, 30).setOffset(0, 15);
            var pt = new Point(x, y, map.spatialReference);
            var infoCont = "<div class='infoCont'>";
            infoCont += area + " <br/>";
            // infoCont += "区" + ": " + area + " <br/>";
            infoCont += `<div id='aroundSearchBtn' class='aroundSearchBtn'><img width='20px' src='img/icon-nearby.png'>周边查询</div>`;

            var infoTemplate = new InfoTemplate("<b>" + addname + "</b>", infoCont);
            var graphic = new Graphic(pt, sms, attr, infoTemplate);

            addressGraphicLayer.add(graphic);
            // addressGraphics.push(graphic)

            var li = document.createElement("li");
            var corp_name = document.createElement("p");
            corp_name.className = "corp_name";
            corp_name.innerHTML = "<img height='25px' src='img/marker2/" + (i + 1 - (page - 1) * onePageCount) + ".png'/>" + "&nbsp" + addname;

            var person_name = document.createElement("p");
            person_name.className = "person_name";
            person_name.innerHTML = area;

            li.appendChild(corp_name);
            li.appendChild(person_name);

            $("#addressList>ul").append(li);

            //第一个点直接聚焦
            if (i - (page - 1) * onePageCount == 0) {
                const center = new Point(x * 1 + 120, y * 1, map.spatialReference);
                map.infoWindow.hide();
                map.infoWindow.setContent(graphic.getContent());
                map.infoWindow.setTitle(graphic.getTitle());
                map.infoWindow.show(pt);
                map.centerAndZoom(center, 6);

                $('#addressList li').removeClass('activeli');
                $('#addressList li:nth-child(2)').addClass('activeli');

                aroundSearchCenterGraphic = graphic;
            }

            (function (li, arg, idx, g) {
                on(li, "click", function () {
                    $('#addressList li').removeClass('activeli');
                    $(li).addClass('activeli');

                    map.graphics.clear();

                    var pt = new Point(arg.x * 1, arg.y * 1, map.spatialReference);
                    var center = new Point(arg.x * 1 + 120, arg.y * 1, map.spatialReference);
                    map.infoWindow.hide();
                    map.infoWindow.setContent(g.getContent());
                    map.infoWindow.setTitle(g.getTitle());
                    map.infoWindow.show(pt);
                    map.centerAndZoom(center, 6);

                    aroundSearchCenterGraphic = g
                });
            })(li, attr, i, graphic);
        }

        // async function showAddressGraphics(addressGraphics) {
        //     for (const item of addressGraphics) {
        //         await addAddressGraphics(item)
        //     }
        // }

        // function addAddressGraphics(graphic) {
        //     return new Promise(function (resolve, reject) {
        //         setTimeout(() => {
        //             addressGraphicLayer.add(graphic);
        //             resolve()
        //         }, 50);
        //     });
        // }

        // showAddressGraphics(addressGraphics)
    }

});